﻿using System.Collections.Generic;
using System.IO;
using Needle.Bus.Messages;
using Needle.Bus.Messages.Management;
using Needle.Utils;

namespace Needle.Bus.Engine.MessageHandlers
{
    public class MessageTracer : IMessageHandler
    {
        private DirectoryInfo _folder;
        private StreamWriter _writer;

        public string Folder
        {
            get { return _folder.FullName; }
            set
            {
                _folder = new DirectoryInfo(value);
                if (!_folder.Exists)
                    _folder.Create();
            }
        }

        public void Initialize()
        {

        }

        public void Process(IMessage message)
        {
            var msg = message as TraceMessage;
            if (msg == null)
                return;
            if (_writer == null)
                OpenWriter();
            _writer.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}",
                msg.Timestamp,
                msg.Source,
                msg.Destination,
                msg.Message is IMessageId ? ((IMessageId)msg.Message).Id : "-",
                msg.Message != null ? msg.Message.GetType().Name : "-");
        }

        public void Process(IList<IMessage> messages)
        {
            foreach (var msg in messages)
                Process(msg);
        }

        private void OpenWriter()
        {
            if (_writer == null)
            {
                if (_folder == null)
                    _folder = AppFileSystem.ExeFolder;
                _writer = new StreamWriter(File.Open(Path.Combine(_folder.FullName, "trace.log"), FileMode.Append, FileAccess.Write, FileShare.Read));
            }
        }

        public void Dispose()
        {
            if (_writer != null)
                _writer.Dispose();
        }
    }
}
